import logging
from logging.handlers import RotatingFileHandler

import redis
from celery import Celery, Task
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO
from config import ProductionConfig, REDIS_DB

db = SQLAlchemy()

socketio = SocketIO()

REDIS_POOL = redis.ConnectionPool(**REDIS_DB)
redis_pool = redis.Redis(connection_pool=REDIS_POOL)


def create_app():
    app = Flask(__name__)
    app.config.from_object(ProductionConfig())
    # 配置日志记录
    handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=1)
    handler.setLevel(logging.INFO)

    formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
    handler.setFormatter(formatter)

    app.logger.addHandler(handler)

    if not app.debug:
        # 如果不处于调试模式，将日志输出到 stdout
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(logging.INFO)
        app.logger.addHandler(stream_handler)
    db.init_app(app)

    socketio.init_app(app)

    from blueprints.user import user_bp
    app.register_blueprint(user_bp)
    from blueprints.home import main_bp
    app.register_blueprint(main_bp)
    from blueprints.bg_task import bg_bp
    app.register_blueprint(bg_bp)

    from blueprints import ws

    return app


